package thread.threadlocal;

/**
 * @program: ch-general
 * @description: 用于父子线程共享变量
 * @author: cuihao
 * @create: 2019-05-28 13:22
 **/
public class MyInheritableThreadLocal {

    private static final InheritableThreadLocal<Object> inheritableThreadLocal = new InheritableThreadLocal<Object>();

    public static void main(String[] args) {
        System.out.println(Thread.currentThread() + " 主线程开始... ");
        inheritableThreadLocal.set(Thread.currentThread() + " Hello World ");
        Thread thread = new Thread(new MyIntegerTask());
        inheritableThreadLocal.set(Thread.currentThread() + " 你好 ");
        // 在线程创建完成后，如果共享变量发生了改变，通过 inheritableThreadLocal 获取的还是之前的值。
        // 也就是说，从父线程把 inheritableThreadLocals 拷贝到子线程后，就跟父线程没有关系了
        thread.start();
    }

    public static class MyIntegerTask implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread() + " 子线程开始... ");
            System.out.println(Thread.currentThread() + " 子线程获取变量: " + inheritableThreadLocal.get());
        }
    }
}